package com.ciban.smarthome.module.engine.base;

import android.content.Context;
import android.database.Cursor;

import com.ciban.smarthome.module.db.DbBaseDao;
import com.ciban.smarthome.module.db.dao.AreaDao;
import com.ciban.smarthome.module.db.dao.EquipmentDao;
import com.ciban.smarthome.module.db.dao.HostDao;
import com.ciban.smarthome.module.entity.Area;
import com.ciban.smarthome.module.entity.Equipment;
import com.ciban.smarthome.module.entity.Host;
import com.ciban.smarthome.module.net.communication.Communicate;
import com.ciban.smarthome.module.utils.ModuleUtils;

public class BaseEngine {
    protected Context context;

    protected BaseEngine(Context context) {
        this.context = context;
    }

    /**
     * 将电器添加到设备表和区域表中
     *
     * @param equip
     */
    protected String addNewEquipMent(Equipment equip) {
        EquipmentDao edao = new EquipmentDao(context);
        AreaDao dao = new AreaDao(context);
        dao.addEquipType(equip.getType(), equip.getArea_id());
        String id = ModuleUtils.getIDByRule();
        equip.setId(id);
        edao.addEquipMentByID(equip);
        edao = null;
        dao = null;
        return id;
    }

    /**
     * 更新电器信息
     *
     * @param equip
     * @return
     */
    protected int upEquipment(Equipment equip) {
        EquipmentDao dao = new EquipmentDao(context);
        int num = dao.updateEquip(equip);
        dao = null;
        return num;
    }

    /**
     * 删除设备
     *
     * @param equip
     * @return
     */
    protected int delEquipment(Equipment equip) {
        EquipmentDao dao = new EquipmentDao(context);
        int num = dao.delEquipMent(equip.getId());
        dao = null;
        return num;
    }

    /**
     * 根据区域id 获取其绑定的主机信息
     *
     * @param area_id
     * @return
     */
    protected Host getHostInfo(String area_id) {
        DbBaseDao bdao = new DbBaseDao(context);
        String sql = "select _id, serial_num, name,ip, port from host where _id=(select host_id from area where _id=?)";
        Cursor cursor = bdao.execRawQuery(sql, new String[]{area_id});
        Host info = null;
        if (cursor != null && cursor.moveToNext()) {
            info = new Host();
            info.setId(cursor.getString(0));
            info.setSerial_no(cursor.getInt(1));
            info.setName(cursor.getString(2));
            info.setIp(cursor.getString(3));
            info.setPort(cursor.getInt(4));
        }

        cursor.close();
        bdao.closeDb();
        bdao = null;

        return info;
    }

    private Communicate conn;

    /**
     * 向服务器发送指令
     *
     * @param cmd
     * @param host
     * @param listener
     */
    protected void sendData(String cmd, Host host, Communicate.ConnListener listener) {
        if (cmd == null || host == null) {
            listener.onFailed("请先添加主机");
            return;
        }
        if (conn == null)
            conn = new Communicate();
        conn.sendData(host, cmd, listener);
    }


}
